package com.huilian.iotbox.admin.service.impl;

import com.huilian.iotbox.admin.dao.PermissionDao;
import com.huilian.iotbox.admin.service.PermissionService;
import com.huilian.iotbox.admin.service.RolePermissionService;
import com.huilian.iotbox.admin.service.UserPermissionService;
import com.huilian.iotbox.data.common.RedisKey;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.enums.PermissionStatusEnum;
import com.huilian.iotbox.data.enums.RoleEnum;
import com.huilian.iotbox.data.po.Permission;
import com.huilian.iotbox.data.vo.UserInfo;
import org.springframework.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 少凡
 * @date 2020/2/26 16:41
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private RolePermissionService rolePermissionService;
    @Autowired
    private UserPermissionService userPermissionService;
    @Autowired
    private RedisTemplate<String, Serializable> redisCacheTemplate;

    @Override
    public ServerResponse getMenus(
            List<Integer> roleIdList,
            Boolean nav,
            String permissionId,
            UserInfo userInfo,
            Integer platformType
    ) {
        //获取角色一级菜单
        List<Permission> topMenus = null;
        List<Permission> childrenMenus = null;
        if(userInfo.getRoleId().equals(RoleEnum.SUB_ACCOUNT.getRoleId())){
            //子账号
            topMenus = permissionDao.findTopMenusByUser(userInfo.getId(), nav, permissionId, platformType);
            childrenMenus = permissionDao.findChildrenMenusByUser(userInfo.getId(), nav, permissionId, userInfo, platformType);
        }else {
            topMenus = permissionDao.findTopMenusByRole(roleIdList, nav, permissionId, platformType);
            childrenMenus = permissionDao.findChildrenMenusByRole(roleIdList, nav, permissionId, userInfo, platformType);
        }

        //给所有顶级类目找儿子
        for (Permission top : topMenus) {
            recursiveTree(top, childrenMenus);
        }

        return ServerResponse.createBySuccess(topMenus);
    }

    @Override
    public ServerResponse getListByRoleId(List<Integer> roleIdList, Boolean noAuth, Integer platformType) {

        //获取角色一级菜单
        List<Permission> topMenus = permissionDao.findTopPermission(roleIdList, platformType);

        List<Permission> childrenMenus = permissionDao.findAllChildren(roleIdList, noAuth, platformType);

        //给所有顶级类目找儿子
        for (Permission top : topMenus) {
            recursiveTree(top, childrenMenus);
        }

        return ServerResponse.createBySuccess(topMenus);
    }

    @Override
    public List<Permission> findNoAuthList(Integer platformType) {
        return permissionDao.findNoAuthList(platformType);
    }


    @Override
    @Transactional
    public ServerResponse add(Permission permission, UserInfo userInfo) {
        if (permission.getNoAuth() == null) {
            permission.setNoAuth(false);
        }

        if (permission.getType().equals("2") && StringUtils.isEmpty(permission.getUrl())) {
            return ServerResponse.createByErrorMessage("权限URL不能为空！");
        }

        if (!StringUtils.isEmpty(permission.getTitle())) {
            permission.setTitle(permission.getTitle().replaceAll(" ", ""));
        }

        if (!StringUtils.isEmpty(permission.getMethod())) {
            permission.setMethod(permission.getMethod().replaceAll(" ", ""));
        }

        if (!StringUtils.isEmpty(permission.getUrl())) {
            permission.setUrl(permission.getUrl().replaceAll(" ", ""));
        }

        Integer result = permissionDao.insert(permission);

        if (result == 1) {
            this.delCache(permission);
            redisCacheTemplate.delete(String.format(RedisKey.PERMISSION_USERID_V2, permission.getPlatformType(), userInfo.getId()));
            return rolePermissionService.authorize(RoleEnum.SUPER_ADMINISTRATOR.getRoleId(), permission.getId());
        } else {
            return ServerResponse.createByErrorMessage("权限添加失败");
        }
    }

    private void delCache(Permission permission) {
        if ("1".equals(permission.getType())) {
            redisCacheTemplate.delete(String.format(RedisKey.PERMISSION_SECOND_STAGE_LIST, permission.getPlatformType(), permission.getParentId()));
            redisCacheTemplate.delete(String.format(RedisKey.PERMISSION_SECOND_STAGE_LIST, permission.getPlatformType(), permission.getId()));
        } else if ("2".equals(permission.getType())) {
            redisCacheTemplate.delete(String.format(RedisKey.PERMISSION_CHILD_API_LIST, permission.getPlatformType(), permission.getParentId()));
        }
    }

    @Override
    public ServerResponse update(Permission permission, UserInfo userInfo) {

        if (!StringUtils.isEmpty(permission.getTitle())) {
            permission.setTitle(permission.getTitle().replaceAll(" ", ""));
        }

        if (!StringUtils.isEmpty(permission.getMethod())) {
            permission.setMethod(permission.getMethod().replaceAll(" ", ""));
        }

        if (!StringUtils.isEmpty(permission.getUrl())) {
            permission.setUrl(permission.getUrl().replaceAll(" ", ""));
        }

        final Permission existPermission = permissionDao.findOnePermissionById(permission.getId());
        if (StringUtils.isEmpty(existPermission)) {
            return ServerResponse.createByErrorMessage("权限不存在");
        }

        Integer result = permissionDao.update(permission);
        if (result == 1) {
            this.delCache(existPermission);
            redisCacheTemplate.delete(String.format(RedisKey.PERMISSION_USERID_V2, permission.getPlatformType(), userInfo.getId()));

            if (!StringUtils.isEmpty(permission.getStatus())) {

                if(
                        PermissionStatusEnum.OPEN.getCode().equals(existPermission.getStatus())
                        && PermissionStatusEnum.CLOSE.getCode().equals(permission.getStatus())
                ){
                    // 下架
                    userPermissionService.updateSelectByPermissionId(existPermission.getId(), false);
                    rolePermissionService.updateSelectByPermissionId(existPermission.getId(), false);
                } else if(
                        PermissionStatusEnum.CLOSE.getCode().equals(existPermission.getStatus())
                                && PermissionStatusEnum.OPEN.getCode().equals(permission.getStatus())
                ){
                    // 上架
                    userPermissionService.updateSelectByPermissionId(existPermission.getId(), true);
                    rolePermissionService.updateSelectByPermissionId(existPermission.getId(), true);
                }
            }
            return ServerResponse.createBySuccess();
        } else {
            return ServerResponse.createByErrorMessage("权限修改失败");
        }
    }

    @Override
    @Transactional
    public ServerResponse delete(Integer id, UserInfo userInfo) {
        final Permission existPermission = permissionDao.findOnePermissionById(id);
        if (StringUtils.isEmpty(existPermission)) {
            return ServerResponse.createByErrorMessage("权限不存在");
        }

        //查看要删除的权限，是否有下级，有的禁止删除
        Integer count = permissionDao.findChildrenCount(id);
        if (count == 0) {
            Integer result = permissionDao.delete(id);
            if (result == 1) {
                this.delCache(existPermission);

                //删除角色权限关联
                rolePermissionService.deleteByPermissionId(id);
                userPermissionService.deleteByPermissionId(id);
                redisCacheTemplate.delete(String.format(RedisKey.PERMISSION_USERID_V2, existPermission.getPlatformType(), userInfo.getId()));
                return ServerResponse.createBySuccess();
            } else {
                return ServerResponse.createByErrorMessage("删除失败！");
            }
        } else {
            return ServerResponse.createByErrorMessage("此权限下面还存在子权限，先删除子权限！");
        }
    }


    //递归无限级
    private Permission recursiveTree(Permission topMenu, List<Permission> childrenMenus) {

        //获取topMenus的儿子
        List<Permission> myChildren = getMyChildren(topMenu, childrenMenus);

        for (Permission child : myChildren) {
            Permission permission = recursiveTree(child, childrenMenus);
            topMenu.getChildren().add(permission);
        }
        return topMenu;
    }

    //直接传allChild进来，不需要，每次都去查询数据库
    private List<Permission> getMyChildren(Permission topMenu, List<Permission> childrenMenus) {

        List<Permission> children = new ArrayList<>();

        for (Permission child : childrenMenus) {
            if (child.getParentId().equals(topMenu.getKey())) {
                children.add(child);
            }
        }

        return children;
    }
}
